package com.example;

import java.util.Optional;

/**
 * @author Liuqz
 * @date 2018/11/17 20:37
 */
public class OptionalUseage {

    public static void main(String[] args) {

        /** 在optionalInsurance 为一个空值,没有存在引用 报空指针异常 */
        /*Optional<Insurance> optionalInsurance = Optional.empty();

        System.out.println(optionalInsurance.get());*/

        /** 在optionalInsurance中存在一个空引用 */
        Optional<Insurance> optionalInsurance = Optional.of(new Insurance());
//        optionalInsurance.get();

        //ofNullable 判断引用对象是否为空
        /*Optional<Insurance> objectOptional = Optional.ofNullable(null);

        //如果对象为空则 GET新建对象
        objectOptional.orElseGet(Insurance::new);

        //如果对象为空 则新建对象
        objectOptional.orElse(new Insurance());

        //如果获取对象为空则 抛出异常
        objectOptional.orElseThrow(RuntimeException::new);

        objectOptional.orElseThrow(() -> new RuntimeException("Note have reference"));*/

        /*
        Insurance insurance =   .filter(i -> i.getName() != null).get();
        System.out.println(insurance);*/

        Optional<String> nameOptional = optionalInsurance.map(Insurance::getName);

        System.out.println(nameOptional.orElse("Empty Value"));

        System.out.println(nameOptional.isPresent());

        nameOptional.ifPresent(System.out::println);


        System.out.println(getInsuranceName(null));
        System.out.println(getInsuranceNameByOptional(null));
    }


    //获取Insurance中的Name
    private static String getInsuranceName(Insurance insurance) {
        if (insurance == null) {
            return "UNKONW";
        }
        return insurance.getName();
    }

    private static String getInsuranceNameByOptional(Insurance insurance) {
        return Optional.ofNullable(insurance).map(e -> e.getName()).orElse("UNKONW");
    }
}
